import 'package:efood_multivendor/controller/auth_controller.dart';
import 'package:efood_multivendor/controller/localization_controller.dart';
import 'package:efood_multivendor/controller/location_controller.dart';
import 'package:efood_multivendor/controller/splash_controller.dart';
import 'package:efood_multivendor/controller/user_controller.dart';
import 'package:efood_multivendor/data/model/response/address_model.dart';
import 'package:efood_multivendor/data/model/response/config_model.dart';
import 'package:efood_multivendor/data/model/response/response_model.dart';
import 'package:efood_multivendor/helper/location_permission.dart';
import 'package:efood_multivendor/helper/responsive_helper.dart';
import 'package:efood_multivendor/helper/route_helper.dart';
import 'package:efood_multivendor/helper/size_config.dart';
import 'package:efood_multivendor/util/dimensions.dart';
import 'package:efood_multivendor/util/images.dart';
import 'package:efood_multivendor/util/styles.dart';
import 'package:efood_multivendor/view/base/custom_button.dart';
import 'package:efood_multivendor/view/base/custom_loader.dart';
import 'package:efood_multivendor/view/base/custom_snackbar.dart';
import 'package:efood_multivendor/view/base/service_unavailable_screen.dart';
import 'package:efood_multivendor/view/screens/address/widget/address_widget.dart';
import 'package:efood_multivendor/view/screens/home/home_screen.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:get/get.dart';
import 'package:shared_preferences/shared_preferences.dart';

class LocationDialog extends StatelessWidget {
  const LocationDialog(
      {Key? key,
      this.isSavedLocationEmpty,
      this.isSavedLocationFound,
      this.locationInput,
      this.locationController,
      this.fromEmptyHome = false})
      : super(key: key);
  final bool? isSavedLocationEmpty;
  final bool? isSavedLocationFound;
  final bool? fromEmptyHome;
  final bool? locationInput;
  final LocationController? locationController;
  @override
  Widget build(BuildContext context) {
    bool _isLoggedIn = Get.find<AuthController>().isLoggedIn();
    if (_isLoggedIn) {
      Get.find<LocationController>().getAddressList();
    }

    TextEditingController _inputAddressController = TextEditingController();
    return Dialog(
      child: Container(
          decoration: BoxDecoration(
            color: Theme.of(context).cardColor,
            borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
          ),
          child: Padding(
              padding: EdgeInsets.all(Dimensions.PADDING_SIZE_LARGE),
              child: isSavedLocationEmpty == true
                  ? Column(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        Text('add_a_delivery'.tr,
                            style: sfMedium.copyWith(
                                fontWeight: FontWeight.bold,
                                fontSize: Dimensions.fontSizeLarge * 1.2)),
                        SizedBox(height: Dimensions.PADDING_SIZE_LARGE),
                        GestureDetector(
                          onTap: () async {
                            LocationPermissionHelper.checkPermission(() async {
                              Get.dialog(CustomLoader(),
                                  barrierDismissible: false);
                              AddressModel? _address =
                                  await Get.find<LocationController>()
                                      .getCurrentLocation(true);
                              ResponseModel? _response =
                                  await Get.find<LocationController>().getZone(
                                      _address?.latitude ?? '',
                                      _address?.longitude ?? '',
                                      false);
                              if (_response?.isSuccess == true) {
                                Get.find<LocationController>()
                                    .updateServiceAble(true);
                                Get.find<LocationController>()
                                    .saveAddressAndNavigateForBottomSheet(
                                        _address!);
                                int timestamp =
                                    DateTime.now().millisecondsSinceEpoch;

                                final prefs =
                                    await SharedPreferences.getInstance();
                                prefs.setInt('LocationTimestamp', timestamp);
                              } else {
                                Get.find<LocationController>()
                                    .updateServiceAble(false);
                                if (Get.find<SplashController>()
                                        .configModel
                                        ?.deadzoneAvailableOrder ==
                                    1) {
                                  // Get.to(ServiceUnavailableScreen());
                                } else {
                                  Get.back();

                                  showCustomSnackBar(
                                      'service_not_available_in_current_location'
                                          .tr);
                                }
                              }
                            });
                          },
                          child: Row(
                            children: [
                              SvgPicture.asset(Images.location_gps,
                                  color:
                                      Theme.of(context).colorScheme.secondary),
                              SizedBox(width: Dimensions.PADDING_SIZE_SMALL),
                              Text('user_current_location'.tr,
                                  style: sfMedium.copyWith(
                                      fontWeight: FontWeight.w600,
                                      fontSize:
                                          Dimensions.fontSizeLarge * 1.1)),
                            ],
                          ),
                        ),
                        SizedBox(
                          height: Dimensions.PADDING_SIZE_LARGE / 1.1,
                        ),
                        GestureDetector(
                          onTap: () {
                            Get.back();
                            if (fromEmptyHome == true) {
                              Get.toNamed(
                                  RouteHelper.getAddAddressRoute(false, true));
                            } else {
                              Get.toNamed(
                                  RouteHelper.getAddAddressRoute(false, true));
                            }
                          },
                          child: Row(
                            children: [
                              Icon(Icons.add,
                                  color:
                                      Theme.of(context).colorScheme.secondary),
                              SizedBox(width: Dimensions.PADDING_SIZE_SMALL),
                              Text('add_a_new_address'.tr,
                                  style: sfMedium.copyWith(
                                      fontWeight: FontWeight.bold,
                                      color: Theme.of(context)
                                          .colorScheme
                                          .secondary,
                                      fontSize:
                                          Dimensions.fontSizeLarge * 1.2)),
                            ],
                          ),
                        )
                      ],
                    )
                  : Column(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        locationInput == true
                            ? Column(
                                mainAxisSize: MainAxisSize.min,
                                children: [
                                  Row(
                                    mainAxisAlignment:
                                        MainAxisAlignment.spaceBetween,
                                    children: [
                                      Text('what_should_we_call_it'.tr.tr,
                                          style: sfMedium.copyWith(
                                              fontWeight: FontWeight.bold,
                                              fontSize:
                                                  Dimensions.fontSizeLarge *
                                                      1.3)),
                                      Container(
                                        decoration: BoxDecoration(
                                          color:
                                              Theme.of(context).disabledColor,
                                          borderRadius:
                                              BorderRadius.circular(2),
                                        ),
                                        child: GestureDetector(
                                            onTap: () {
                                              Get.back();
                                            },
                                            child: Center(
                                              child: Icon(Icons.close),
                                            )),
                                      )
                                    ],
                                  ),
                                  Divider(),
                                  SizedBox(
                                      height: Dimensions.PADDING_SIZE_LARGE),
                                  Container(
                                    child: Row(
                                      children: [
                                        Expanded(
                                          flex: 3,
                                          child: Container(
                                            decoration: BoxDecoration(
                                              border: Border.all(
                                                  color: Theme.of(context)
                                                      .disabledColor,
                                                  width: 1),
                                              borderRadius:
                                                  BorderRadius.circular(10),
                                            ),
                                            child: TextFormField(
                                              controller:
                                                  _inputAddressController,
                                              style: sfRegular.copyWith(
                                                  height:
                                                      ResponsiveHelper.isMobile(
                                                              context)
                                                          ? null
                                                          : 2),
                                              decoration: InputDecoration(
                                                hintText: 'new_address'.tr,
                                                hintStyle: sfRegular.copyWith(
                                                    color: Theme.of(context)
                                                        .hintColor),
                                                isDense: true,
                                                filled: true,
                                                fillColor:
                                                    Theme.of(context).cardColor,
                                                border: OutlineInputBorder(
                                                  borderRadius:
                                                      BorderRadius.all(
                                                    Radius.circular(Get.find<
                                                                LocalizationController>()
                                                            .isLtr
                                                        ? 10
                                                        : 0),
                                                  ),
                                                  borderSide: BorderSide.none,
                                                ),
                                              ),
                                            ),
                                          ),
                                        ),
                                        SizedBox(
                                          width: 10,
                                        ),
                                        Expanded(
                                          child: CustomButton(
                                            onPressed: () async {
                                              Get.back();
                                              AddressModel _addressModel =
                                                  AddressModel(
                                                id: null,
                                                addressType:
                                                    _inputAddressController
                                                        .text,
                                                contactPersonName:
                                                    Get.find<UserController>()
                                                        .userInfoModel
                                                        ?.fName,
                                                contactPersonNumber:
                                                    Get.find<UserController>()
                                                        .userInfoModel
                                                        ?.phone,
                                                address:
                                                    locationController?.address,
                                                latitude: locationController
                                                        ?.position.latitude
                                                        .toString() ??
                                                    '',
                                                longitude: locationController
                                                        ?.position.longitude
                                                        .toString() ??
                                                    '',
                                                zoneId:
                                                    locationController?.zoneID,
                                              );

                                              ResponseModel? _response =
                                                  await Get.find<
                                                          LocationController>()
                                                      .getZone(
                                                          _addressModel
                                                                  .latitude ??
                                                              '',
                                                          _addressModel
                                                                  .longitude ??
                                                              '',
                                                          false);
                                              if (_response?.isSuccess ==
                                                  true) {
                                                Get.find<LocationController>()
                                                    .updateServiceAble(true);
                                                Get.find<LocationController>()
                                                    .saveAddressAndNavigate(
                                                        _addressModel,
                                                        true,
                                                        "",
                                                        Get.currentRoute
                                                            .isNotEmpty);
                                              } else {
                                                Get.find<LocationController>()
                                                    .updateServiceAble(false);
                                                if (Get.find<SplashController>()
                                                        .configModel
                                                        ?.deadzoneAvailableOrder ==
                                                    1) {
                                                  // Get.to(
                                                  //     ServiceUnavailableScreen());
                                                } else {
                                                  Get.back();
                                                  Get.toNamed(RouteHelper
                                                      .getPickMapRoute(
                                                          Get.currentRoute
                                                                  .isEmpty
                                                              ? RouteHelper
                                                                  .accessLocation
                                                              : Get
                                                                  .currentRoute,
                                                          Get.currentRoute
                                                              .isNotEmpty));
                                                  showCustomSnackBar(
                                                      'service_not_available_in_current_location'
                                                          .tr);
                                                }
                                              }
                                              locationController
                                                  ?.addAddress(
                                                      _addressModel, false)
                                                  .then((response) {
                                                if (response.isSuccess) {
                                                  Get.back();

                                                  showCustomSnackBar(
                                                      'new_address_added_successfully'
                                                          .tr,
                                                      isError: false);
                                                } else {
                                                  showCustomSnackBar(
                                                      response.message);
                                                }
                                              });
                                            },
                                            buttonText: 'save'.tr,
                                          ),
                                        )
                                      ],
                                    ),
                                  ),
                                ],
                              )
                            : GetBuilder<LocationController>(
                                builder: (locationController) {
                                return Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Text(
                                      'where_is_your'.tr,
                                      textAlign: TextAlign.center,
                                      style: sfMedium.copyWith(
                                          fontWeight: FontWeight.bold,
                                          fontSize:
                                              Dimensions.fontSizeExtraLarge),
                                    ),
                                    SizedBox(
                                      height: 10,
                                    ),
                                    Column(
                                      children: [
                                        ListTile(
                                          onTap: () async {
                                            Get.find<SplashController>()
                                                .setFirstOpen();
                                            LocationPermissionHelper
                                                .checkPermission(() async {
                                              Get.dialog(CustomLoader(),
                                                  barrierDismissible: false);
                                              AddressModel? _address =
                                                  await Get.find<
                                                          LocationController>()
                                                      .getCurrentLocation(true);
                                              ResponseModel? _response =
                                                  await Get.find<
                                                          LocationController>()
                                                      .getZone(
                                                          _address?.latitude ??
                                                              '',
                                                          _address?.longitude ??
                                                              '',
                                                          false);
                                              if (_response?.isSuccess ==
                                                  true) {
                                                Get.find<LocationController>()
                                                    .updateServiceAble(true);
                                                Get.find<LocationController>()
                                                    .saveAddressAndNavigateForBottomSheet(
                                                        _address!);
                                                int timestamp = DateTime.now()
                                                    .millisecondsSinceEpoch;

                                                final prefs =
                                                    await SharedPreferences
                                                        .getInstance();
                                                prefs.setInt(
                                                    'LocationTimestamp',
                                                    timestamp);
                                              } else {
                                                Get.find<LocationController>()
                                                    .updateServiceAble(false);
                                                if (Get.find<SplashController>()
                                                        .configModel
                                                        ?.deadzoneAvailableOrder ==
                                                    1) {
                                                  // Get.to(
                                                  //     ServiceUnavailableScreen());
                                                } else {
                                                  Get.back();
                                                  showCustomSnackBar(
                                                      'service_not_available_in_current_location'
                                                          .tr);
                                                }
                                              }
                                            });
                                          },
                                          leading: SvgPicture.asset(
                                              Images.location_gps,
                                              color: Theme.of(context)
                                                  .colorScheme
                                                  .secondary),
                                          minLeadingWidth: 0,
                                          title: Text(
                                            "user_current_location".tr,
                                            style: sfRegular.copyWith(
                                                fontWeight: FontWeight.w600,
                                                fontSize:
                                                    Dimensions.fontSizeSmall *
                                                        1.3),
                                          ),
                                          horizontalTitleGap: 2.8.w,
                                        ),
                                        locationController.addressList.length <=
                                                4
                                            ? ListView.builder(
                                                padding: EdgeInsets.all(
                                                    Dimensions
                                                        .PADDING_SIZE_SMALL),
                                                physics:
                                                    BouncingScrollPhysics(),
                                                itemCount: locationController
                                                    .addressList.length,
                                                shrinkWrap: true,
                                                itemBuilder: (context, index) {
                                                  return Center(
                                                      child: SizedBox(
                                                          width: 700,
                                                          child: AddressWidget(
                                                            fromSetting: false,
                                                            address:
                                                                locationController
                                                                        .addressList[
                                                                    index],
                                                            fromAddress: false,
                                                            onTap: () {
                                                              Get.find<
                                                                      SplashController>()
                                                                  .setFirstOpen();
                                                              Get.dialog(
                                                                  CustomLoader(),
                                                                  barrierDismissible:
                                                                      false);
                                                              AddressModel
                                                                  _address =
                                                                  locationController
                                                                          .addressList[
                                                                      index];
                                                              locationController
                                                                  .saveAddressAndNavigate(
                                                                      _address,
                                                                      false,
                                                                      "",
                                                                      Get.currentRoute
                                                                          .isNotEmpty);
                                                              Get.find<
                                                                      SplashController>()
                                                                  .loadData(
                                                                      true);
                                                            },
                                                          )));
                                                },
                                              )
                                            : Container(
                                                height: 30.h,
                                                child: ListView.builder(
                                                  padding: EdgeInsets.all(
                                                      Dimensions
                                                          .PADDING_SIZE_SMALL),
                                                  physics:
                                                      BouncingScrollPhysics(),
                                                  itemCount: locationController
                                                      .addressList.length,
                                                  shrinkWrap: true,
                                                  itemBuilder:
                                                      (context, index) {
                                                    return Center(
                                                        child: SizedBox(
                                                            width: 700,
                                                            child:
                                                                AddressWidget(
                                                              fromSetting:
                                                                  false,
                                                              address:
                                                                  locationController
                                                                          .addressList[
                                                                      index],
                                                              fromAddress:
                                                                  false,
                                                              onTap: () {
                                                                Get.dialog(
                                                                    CustomLoader(),
                                                                    barrierDismissible:
                                                                        false);
                                                                AddressModel
                                                                    _address =
                                                                    locationController
                                                                            .addressList[
                                                                        index];
                                                                locationController
                                                                    .saveAddressAndNavigate(
                                                                        _address,
                                                                        false,
                                                                        "",
                                                                        Get.currentRoute
                                                                            .isNotEmpty);
                                                              },
                                                            )));
                                                  },
                                                ),
                                              ),
                                      ],
                                    ),
                                    SizedBox(
                                        height: Dimensions.PADDING_SIZE_LARGE),
                                    GestureDetector(
                                      onTap: () {
                                        Get.back();
                                        Get.toNamed(
                                            RouteHelper.getAddAddressRoute(
                                                false, false));
                                      },
                                      child: Row(
                                        children: [
                                          SizedBox(
                                              width: Dimensions
                                                      .PADDING_SIZE_SMALL *
                                                  1.8),
                                          Icon(Icons.add,
                                              color: Theme.of(context)
                                                  .colorScheme
                                                  .secondary),
                                          SizedBox(
                                              width: Dimensions
                                                      .PADDING_SIZE_SMALL *
                                                  1),
                                          Text('add_a_new_address'.tr,
                                              style: sfMedium.copyWith(
                                                  fontWeight: FontWeight.bold,
                                                  fontSize:
                                                      Dimensions.fontSizeLarge *
                                                          1.1)),
                                        ],
                                      ),
                                    )
                                  ],
                                );
                              })
                      ],
                    ))),
    );
  }
}
